<?php
/**
 * SyncService.php class file.
 * @author shengxia <523247758@qq.com>
 * @date 2020/01/07- 2:33 下午
 */

namespace common\services;


use common\dao\PddMallLogisticsDao;
use common\models\PddMallProductSkus;
use common\models\PddMallLogistics;
use common\components\api\isv\Goods;
use common\helpers\AmountHelper;

class SyncProductbatchDetailService
{

    /**
     * 复制商品
     * @inheritDoc
     * @throws \common\exception\ServicesException
     */
    public function copy($goodsDetail, $batchInfo, $update = 0)
    {

        $insertProduct['origin_country_id'] = $goodsDetail['origin_country_id'];
        $insertProduct['delivery_type'] = $goodsDetail['delivery_type'];
        $insertProduct['order_limit'] = $goodsDetail['order_limit'];
        $insertProduct['customer_num'] = $goodsDetail['customer_num'];
        $insertProduct['buy_limit'] = $goodsDetail['buy_limit'];
        $insertProduct['pre_sale_time'] = $goodsDetail['pre_sale_time'];
        $insertProduct['status'] = $goodsDetail['status'];
        $insertProduct['carousel_gallery'] = $goodsDetail['carousel_gallery_list'];
        $insertProduct['cat_id'] = $goodsDetail['cat_id'];
        $insertProduct['cost_template_id'] = $goodsDetail['cost_template_id'];
        $insertProduct['country_id'] = $goodsDetail['country_id'] ?? 0;
        $insertProduct['detail_gallery_list'] = $goodsDetail['detail_gallery_list'];
        $insertProduct['goods_desc'] = $goodsDetail['goods_desc'] ?? '';
        $insertProduct['goods_id'] = $goodsDetail['goods_id'];
        $insertProduct['goods_name'] = $goodsDetail['goods_name'];
        $insertProduct['tiny_name'] = $goodsDetail['tiny_name'];
        $insertProduct['goods_type'] = $goodsDetail['goods_type'] ?? 0;
        $insertProduct['is_folt'] = ($goodsDetail['is_folt'] == 1) ? 'true' : 'false';
        $insertProduct['is_pre_sale'] = $goodsDetail['is_pre_sale'] == 1 ? 'true' : 'false';
        $insertProduct['is_refundable'] = $goodsDetail['is_refundable'] == 1 ? 'true' : 'false';
        $insertProduct['market_price'] = AmountHelper::fenToYuan($goodsDetail['market_price']);
        $insertProduct['second_hand'] = $goodsDetail['second_hand'] == 1 ? 'true' : 'false';
        $insertProduct['shipment_limit_second'] = $goodsDetail['shipment_limit_second'] ?? 0;
        $skuInfo = PddMallProductSkus::findAll(['goods_id' => $goodsDetail['goods_id']]);


        if ($skuInfo) {
            $sku = array();
            foreach ($skuInfo as $k => $v) {
                $skuOld = $v->toArray();
                $spec = $skuOld['spec'];
                $specArr = array();
                if ($spec) {
                    $specArr = json_decode($spec, true);
                }
                $specStr = array();
                $spec_id_list = '[]';
                if ($specArr) {
                    foreach ($specArr as $key => $val) {
                        $specStr[] = $val['spec_id'];
                    }
                    $spec_id_list = json_encode($specStr);
                }
                $skuNew = array(
                    'is_onsale' => $skuOld['is_onsale'],
                    'limit_quantity' => $skuOld['limit_quantity'],
                    'multi_price' => $skuOld['multi_price'],
                    'price' => $skuOld['price'],
                    'quantity' => 0,
                    'sku_id' => $skuOld['sku_id'],
                    'thumb_url' => $skuOld['thumb_url'],
                    'weight' => $skuOld['weight'],
                    'spec_id_list' => $spec_id_list
                );
                $sku[] = $skuNew;

            }
            $insertProduct['sku_list'] = json_encode($sku, true);
        }
        //获取批量修改的任务信息
        if ($batchInfo) {
            $list[] = $insertProduct;
            $batchType = $batchInfo['batchType'];
            $actionName = 'getBatch' . $batchType;
            $args = array(
                'uid' => $batchInfo['uid'],
                'mall_id' => $batchInfo['mall_id'],
                'contentType' => $batchInfo['contentType'],
                'inputPrefix' => $batchInfo['inputPrefix'],
                'inputSuffix' => $batchInfo['inputSuffix'],
                'deleteTitleOverLengthSource' => $batchInfo['deleteTitleOverLengthSource'],
                'deleteTitleOverLengthPos' => $batchInfo['deleteTitleOverLengthPos'],
                'inputReplace' => json_decode($batchInfo['inputReplace'], true),
                'inputSearch' => json_decode($batchInfo['inputSearch'], true),
                'inputNewContent' => $batchInfo['inputNewContent'],
                'filterKeyword' => $batchInfo['filterKeyword'],
                'replacePrefix' => $batchInfo['replacePrefix'],
                'replaceSuffix' => $batchInfo['replaceSuffix'],
                'editGoodsJson' => $batchInfo['editGoodsJson'],
                'delGoodsJson' => $batchInfo['delGoodsJson'],
                'isonsale' => $batchInfo['isonsale'],
                'autooffline' => $batchInfo['autooffline'],
                'presaletime' => $batchInfo['presaledate'],
                'presale' => $batchInfo['presale'],
                'countryId' => $batchInfo['countryId'],
                'countryType' => $batchInfo['countryType'],
                'templateid' => $batchInfo['template_id'],
                'deliverytype' => $batchInfo['delivery_type'],
                'new_buy_limit' => $batchInfo['buy_limit'],
                'new_order_limit' => $batchInfo['order_limit'],
                'new_customer_num' => $batchInfo['customer_num'],
                'new_is_folt' => $batchInfo['is_folt'],
                'new_second_hand' => $batchInfo['second_hand'],
                'new_is_refundable' => $batchInfo['is_refundable'],
                'new_shipment_limit_second' => $batchInfo['shipment_limit_second'],
                'inputMultiplierPrice' => $batchInfo['inputMultiplierPrice'],
                'inputAddPrice' => $batchInfo['inputAddPrice'],
                'inputSubPrice' => $batchInfo['inputSubPrice'],
                'inputLastMultiplierPrice' => $batchInfo['inputLastMultiplierPrice'],
                'priceRounding' => $batchInfo['priceRounding'],
                'priceTail' => $batchInfo['priceTail'],
            );
            $batchRes = (new MallProductService())->$actionName($list, $args, $update);
            unset($insertProduct['tiny_name']);
            if ($batchRes) {
                if (isset($batchRes[0]['new_goods_name'])) {
                    if ($batchRes[0]['new_goods_name'] == $batchRes[0]['goods_name']) {
                        $res = array(
                            'error_code' => 4,
                            'error_info' => '没有发生任何修改，跳过'
                        );
                        $res['updateInfo'] = $batchRes;
                        return $res;
                    } else {
                        $insertProduct['goods_name'] = $batchRes[0]['new_goods_name'];
                    }
                }
                if (isset($batchRes[0]['new_tiny_name'])) {
                    if ($batchRes[0]['new_tiny_name'] == $batchRes[0]['tiny_name']) {
                        $res = array(
                            'error_code' => 4,
                            'error_info' => '没有发生任何修改，跳过'
                        );
                        $res['updateInfo'] = $batchRes;
                        return $res;
                    } else {
                        $insertProduct['tiny_name'] = $batchRes[0]['new_tiny_name'];
                    }
                }
                //是否预售
                if (isset($batchRes[0]['new_is_pre_sale'])) {
                    if ($batchRes[0]['new_is_pre_sale'] == $batchRes[0]['is_pre_sale'] && $batchRes[0]['pre_sale_time'] == $batchRes[0]['new_presaletime']) {
                        $res = array(
                            'error_code' => 4,
                            'error_info' => '没有发生任何修改，跳过'
                        );
                        $res['updateInfo'] = $batchRes;
                        return $res;
                    } else {
                        $insertProduct['is_pre_sale'] = $batchRes[0]['new_is_pre_sale'] == 1 ? 'true' : 'false';
                        if ($batchRes[0]['new_is_pre_sale'] == 1) {
                            unset($insertProduct['shipment_limit_second']);
                        }
                        if ($insertProduct['is_pre_sale'] == 'false') {
                            $insertProduct['pre_sale_time'] = 0;
                        }
                    }
                }
                if (isset($batchRes[0]['new_presaletime'])) {
                    $insertProduct['pre_sale_time'] = strtotime($batchRes[0]['new_presaletime']) ? strtotime($batchRes[0]['new_presaletime']) : 0;
                }
                if (isset($batchRes[0]['new_countryType']) && !empty($batchRes[0]['new_countryType'])) {
                    $insertProduct['goods_type'] = $batchRes[0]['new_countryType'];
                }
                if (isset($batchRes[0]['new_origin_country_id']) && !empty($batchRes[0]['new_origin_country_id'])) {
                    if ($batchRes[0]['origin_country_id'] == $batchRes[0]['new_origin_country_id']) {
                        $res = array(
                            'error_code' => 4,
                            'error_info' => '没有发生任何修改，跳过'
                        );
                        $res['updateInfo'] = $batchRes;
                        return $res;
                    } else {
                        $insertProduct['origin_country_id'] = $batchRes[0]['new_origin_country_id'];
                    }

                }
                if (isset($batchRes[0]['new_cost_template_id']) && !empty($batchRes[0]['new_cost_template_id'])) {

                    if ($batchRes[0]['cost_template_id'] == $batchRes[0]['new_cost_template_id']) {
                        $res = array(
                            'error_code' => 4,
                            'error_info' => '没有发生任何修改，跳过'
                        );
                        $res['updateInfo'] = $batchRes;
                        return $res;
                    } else {
                        $insertProduct['cost_template_id'] = $batchRes[0]['new_cost_template_id'];
                    }
                }
                if (isset($batchRes[0]['new_delivery_type'])) {

                    if ($batchRes[0]['delivery_type'] == $batchRes[0]['new_delivery_type']) {
                        $res = array(
                            'error_code' => 4,
                            'error_info' => '没有发生任何修改，跳过'
                        );
                        $res['updateInfo'] = $batchRes;
                        return $res;
                    } else {
                        $insertProduct['delivery_type'] = $batchRes[0]['new_delivery_type'];
                    }

                }
                //市场价
                if (isset($batchRes[0]['new_market_price'])) {
                    if ($batchRes[0]['market_price'] == $batchRes[0]['new_market_price']) {
                        $res = array(
                            'error_code' => 4,
                            'error_info' => '没有发生任何修改，跳过'
                        );
                        $res['updateInfo'] = $batchRes;
                        return $res;
                    } else {
                        $insertProduct['market_price'] = $batchRes[0]['new_market_price'] * 100;
                    }
                }

                //服务承诺
                if ($batchType == 'other') {
                    //是否二手
                    $otherarr = array(
                        'new_buy_limit' => '',
                        'buy_limit' => '',
                        'new_order_limit' => '',
                        'order_limit' => '',
                        'customer_num' => '',
                        'new_customer_num' => '',
                        'is_folt' => '',
                        'new_is_folt' => '',
                        'is_refundable' => '',
                        'new_is_refundable' => '',
                        'shipment_limit_second' => '',
                        'new_shipment_limit_second' => '',
                        'second_hand' => '',
                        'new_second_hand' => ""
                    );
                    if (isset($batchRes[0]['new_buy_limit']) && is_numeric($batchRes[0]['new_buy_limit'])) {
                        $insertProduct['buy_limit'] = $batchRes[0]['new_buy_limit'];
                        $otherarr['new_buy_limit'] = $batchRes[0]['new_buy_limit'];
                        $otherarr['buy_limit'] = $batchRes[0]['buy_limit'];
                    }
                    if (isset($batchRes[0]['new_order_limit']) && is_numeric($batchRes[0]['new_order_limit'])) {
                        $insertProduct['order_limit'] = $batchRes[0]['new_order_limit'];
                        $otherarr['new_order_limit'] = $batchRes[0]['new_order_limit'];
                        $otherarr['order_limit'] = $batchRes[0]['order_limit'];
                    }
                    if (isset($batchRes[0]['new_customer_num']) && is_numeric($batchRes[0]['new_customer_num'])) {
                        $insertProduct['customer_num'] = $batchRes[0]['new_customer_num'];
                        $otherarr['customer_num'] = $batchRes[0]['customer_num'];
                        $otherarr['new_customer_num'] = $batchRes[0]['new_customer_num'];
                    }
                    if (isset($batchRes[0]['new_is_folt']) && is_numeric($batchRes[0]['new_is_folt'])) {
                        $insertProduct['is_folt'] = $batchRes[0]['new_is_folt'] ? 'true' : 'false';
                        $otherarr['is_folt'] = $batchRes[0]['is_folt'] == 'true' ? 1 : 0;
                        $otherarr['new_is_folt'] = $batchRes[0]['new_is_folt'];
                    }
                    if (isset($batchRes[0]['new_is_refundable']) && is_numeric($batchRes[0]['new_is_refundable'])) {
                        $insertProduct['is_refundable'] = $batchRes[0]['new_is_refundable'] ? 'true' : 'false';
                        $otherarr['is_refundable'] = $batchRes[0]['is_refundable'] == 'true' ? 1 : 0;
                        $otherarr['new_is_refundable'] = $batchRes[0]['new_is_refundable'];
                    }
                    if (isset($batchRes[0]['new_shipment_limit_second']) && is_numeric($batchRes[0]['new_shipment_limit_second'])) {
                        $insertProduct['shipment_limit_second'] = $batchRes[0]['new_shipment_limit_second'];
                        $otherarr['shipment_limit_second'] = $batchRes[0]['shipment_limit_second'];
                        $otherarr['new_shipment_limit_second'] = $batchRes[0]['new_shipment_limit_second'];
                    }
                    if (isset($batchRes[0]['new_second_hand']) && is_numeric($batchRes[0]['new_second_hand'])) {
                        $insertProduct['second_hand'] = $batchRes[0]['new_second_hand'] ? 'true' : 'false';
                        $otherarr['second_hand'] = $batchRes[0]['second_hand'] == 'true' ? 1 : 0;
                        $otherarr['new_second_hand'] = $batchRes[0]['new_second_hand'];
                    }
                    if ($otherarr['buy_limit'] == $otherarr['new_buy_limit'] && $otherarr['order_limit'] == $otherarr['new_order_limit'] && $otherarr['customer_num'] == $otherarr['new_customer_num'] && $otherarr['is_folt'] == $otherarr['new_is_folt'] && $otherarr['is_refundable'] == $otherarr['new_is_refundable'] && $otherarr['shipment_limit_second'] == $otherarr['new_shipment_limit_second'] && $otherarr['second_hand'] == $otherarr['new_second_hand']) {
                        $res = array(
                            'error_code' => 4,
                            'error_info' => '没有发生任何修改，跳过'
                        );
                        $res['updateInfo'][0] = $otherarr;
                        return $res;
                    }
                }


            }
        }
        if ($batchInfo['batchType'] == 'onsale') {
            //批量上下架接口
            if (isset($batchRes[0]['newstatus'])) {
                if ($batchRes[0]['newstatus'] == $batchRes[0]['status']) {
                    $res = array(
                        'error_code' => 4,
                        'error_info' => '没有发生任何修改，跳过'
                    );
                    $res['updateInfo'] = $batchRes;
                    return $res;
                } else {
                    try {
                        $res = (new Goods())->pddGoodsSaleStatusSet($goodsDetail['goods_id'], intval($batchRes[0]['newstatus']) == 2 ? 0 : 1, $goodsDetail['mall_id']);
                        if ($res) {
                            $insertProduct['status'] = $batchRes[0]['newstatus'];
                        }
                    } catch (\yii\base\Exception $e) {
                        $res = array(
                            'error_code' => 2,
                            'error_info' => $e->getMessage()
                        );
                        $res['updateInfo'] = $batchRes;
                        return $res;
                    }

                }
            }
        } else if ($batchInfo['batchType'] == 'goodsdelete') {
            //批量上下架接口
//            $idsdeleteJson = $batchInfo['ids'];
//            $idsdeleteArr = array();
//            if($idsdeleteJson){
//                $idsdeleteArr = explode(',',$batchInfo['ids']);
//            }
//            if($idsdeleteArr){
//
//            }
            $autooffline = $batchInfo['autooffline'];
            //在售商品是否删除
            if ($autooffline) {
                if ($goodsDetail['status'] == 1) {
                    try {
                        (new Goods())->pddGoodsSaleStatusSet($goodsDetail['goods_id'], 0, $goodsDetail['mall_id']);
                    } catch (\yii\base\Exception $e) {
                        $res = array(
                            'error_code' => 2,
                            'error_info' => $e->getMessage()
                        );
                        $res['updateInfo'] = $batchRes;
                        return $res;
                    }

                }
                $arr = array($goodsDetail['goods_id']);
                try {
                    $res = (new Goods())->pddGoodsDelete(json_encode($arr), $goodsDetail['mall_id']);
                } catch (\yii\base\Exception $e) {
                    $res = array(
                        'error_code' => 2,
                        'error_info' => $e->getMessage()
                    );
                    $res['updateInfo'] = $batchRes;
                    return $res;
                }

            } else {
                if ($goodsDetail['status'] == 1 || $goodsDetail['status'] == 3) {
                    //上架跳过
                    $res = array(
                        'error_code' => 2,
                        'error_info' => '已跳过上架商品'
                    );
                } else {
                    $arr = array($goodsDetail['goods_id']);
                    $res = (new Goods())->pddGoodsDelete(json_encode($arr), $goodsDetail['mall_id']);
                }
            }

        } else {
            if (isset($insertProduct['market_price'])) {
                $insertProduct['market_price'] = $insertProduct['market_price'] * 100;
            }
            try {
                $res = (new Goods())->pddGoodsUpdate($insertProduct, $goodsDetail['mall_id']);
            } catch (\yii\base\Exception $e) {
                $res = array(
                    'error_code' => 2,
                    'error_info' => $e->getMessage()
                );
                $res['updateInfo'] = $batchRes;
                return $res;
            }
        }
        if ($res) {
            if (isset($res['is_success']) && $res['is_success'] == 1) {
                $insertProduct = array();
                $insertProduct['goods_id'] = $goodsDetail['goods_id'];
                if (isset($batchRes[0]['new_goods_name'])) {
                    $insertProduct['goods_name'] = $batchRes[0]['new_goods_name'];
                }
                if (isset($batchRes[0]['new_tiny_name'])) {
                    $insertProduct['tiny_name'] = $batchRes[0]['new_tiny_name'];
                }
                if (isset($batchRes[0]['newstatus'])) {
                    $insertProduct['status'] = $batchRes[0]['newstatus'] == 1 ? 1 : 2;
                }
                if (isset($batchRes[0]['new_is_pre_sale'])) {
                    $insertProduct['is_pre_sale'] = $batchRes[0]['new_is_pre_sale'];
                }
                if (isset($batchRes[0]['new_presaletime'])) {
                    $insertProduct['pre_sale_time'] = strtotime($batchRes[0]['new_presaletime']) ? strtotime($batchRes[0]['new_presaletime']) : 0;
                }
                if (isset($batchRes[0]['new_cost_template_id']) && !empty($batchRes[0]['new_cost_template_id'])) {
                    $insertProduct['cost_template_id'] = $batchRes[0]['new_cost_template_id'];
                }
                if (isset($batchRes[0]['new_delivery_type'])) {
                    $insertProduct['delivery_type'] = $batchRes[0]['new_delivery_type'];
                }


                if (isset($batchRes[0]['new_buy_limit']) && is_numeric($batchRes[0]['new_buy_limit'])) {
                    $insertProduct['buy_limit'] = $batchRes[0]['new_buy_limit'];
                }
                if (isset($batchRes[0]['new_order_limit']) && is_numeric($batchRes[0]['new_order_limit'])) {
                    $insertProduct['order_limit'] = $batchRes[0]['new_order_limit'];
                }
                if (isset($batchRes[0]['new_customer_num']) && is_numeric($batchRes[0]['new_customer_num'])) {
                    $insertProduct['customer_num'] = $batchRes[0]['new_customer_num'];
                }
                if (isset($batchRes[0]['new_is_folt']) && is_numeric($batchRes[0]['new_is_folt'])) {
                    $insertProduct['is_folt'] = $batchRes[0]['new_is_folt'];
                }
                if (isset($batchRes[0]['new_is_refundable']) && is_numeric($batchRes[0]['new_is_refundable'])) {
                    $insertProduct['is_refundable'] = $batchRes[0]['new_is_refundable'];
                }
                if (isset($batchRes[0]['new_shipment_limit_second']) && is_numeric($batchRes[0]['new_shipment_limit_second'])) {
                    $insertProduct['shipment_limit_second'] = $batchRes[0]['new_shipment_limit_second'];
                }
                if (isset($batchRes[0]['new_second_hand']) && is_numeric($batchRes[0]['new_second_hand'])) {
                    $insertProduct['second_hand'] = $batchRes[0]['new_second_hand'];
                }
                if (isset($batchRes[0]['new_market_price'])) {
                    if (intval($batchRes[0]['new_market_price'] * 100) > 0) {
                        $insertProduct['market_price'] = $batchRes[0]['new_market_price'] * 100;
                    }
                }

                $insertSkus = [];
                //更新本地数据库
                (new SyncService())->syncProducts($insertProduct, $insertSkus);
            }

            if (isset($res['open_api_response']) && $res['open_api_response'] == 1) {
                $insertProduct = array();
                $insertProduct['goods_id'] = $goodsDetail['goods_id'];
                $insertProduct['status'] = 4;
                $insertSkus = [];
                //更新本地数据库
                (new SyncService())->syncProducts($insertProduct, $insertSkus);
            }
        }
        $res['updateInfo'] = $batchRes;
        return $res;
    }


    /**
     * 同步商品运费模板
     * @param array $logistics
     * @return PddMallLogistics|null
     * @throws \api\exceptions\ValidatorException
     */
    public function syncLogistics(array $logistics)
    {

        $mallLogistics = new PddMallLogisticsDao();

        $mallLogisticsInfo = $mallLogistics->getInfoByTmplateId($logistics['template_id']);


        if (!$mallLogisticsInfo) {
            $mallLogisticsInfo = $mallLogistics->insertData($logistics);
        } else {

            $mallLogistics->updateData($mallLogisticsInfo, $logistics);
        }

        return $mallLogisticsInfo;

    }

}
